<?php
namespace Home\Controller;
class OrderController extends CommonController{
	/* 获取订单日志 */
	public function getOrderLog(){
		$mustData = array(
			'or_id'=>$_POST['orderId'],
		);
		$limit = $_POST['limit']?$_POST['limit']:1;
		CheckMustData($mustData);
		$dataList = M('OrderLog')->where(array('ol_order_id'=>$_POST['orderId']))->order("ol_create_time desc")->limit($limit)->select();
		foreach ($dataList as $key => $value) {
			$dataList[$key]['ol_create_time'] = date("Y-m-d H:i:s",$value['ol_create_time']);
		}
		ApiResult(200,array('dataList'=>$dataList));
	}

	/*提交新的账号密码或者短信验证码*/
	public function updateOrderGameInfo(){
		$mustData = array(
			'or_id'=>$_POST['orderId'],
		);
		CheckMustData($mustData);
		$data = M('Order')->where(array('or_id'=>$_POST['orderId']))->find();
		$saveData = array();
		if($_POST['account']!=null){
			$saveData['or_account']=$_POST['account'];
		}
		if($_POST['password']!=null){
			$saveData['or_password']=$_POST['password'];
		}
		if($_POST['code']!=null){
			$saveData['or_code']=$_POST['code'];
		}
		if(empty($saveData)){
			ApiResult(301);
		}
		$result = M('Order')->where(array('or_id'=>$_POST['orderId']))->save($saveData);
		
		ApiResult(200);
	}
	/*修改订单参数*/
	public function updateOrderParams(){
		$mustData = array(
			'or_id'=>$_POST['orderId'],
			'key'=>$_POST['key'],
			'value'=>$_POST['value'],
		);
		CheckMustData($mustData);
		$order = M('Order')->where(array('or_id'=>$_POST['orderId']))->find();
		if(empty($order)){
			ApiResult(300);
		}
		$param = $order['or_param'];
		$param = json_decode($param,true);
		$param[$_POST['key']] = $_POST['value'];
		$result = M('Order')->where(array('or_id'=>$_POST['orderId']))->save(array('or_param'=>json_encode($param)));
		
		ApiResult(200);
	}
	/*更改游戏状态*/
	public function updateGameStatus(){
		$mustData = array(
			'or_id'=>$_POST['orderId'],
			'status'=>$_POST['status'],
		);
		CheckMustData($mustData);
		$order = M('Order')->where(array('or_id'=>$_POST['orderId']))->find();
		if(empty($order)){
			ApiResult(300);
		}
		if((int)$_POST['status'] == 1 ||(int)$_POST['status'] == 2){
			$result = M('Order')->where(array('or_id'=>$_POST['orderId']))->save(array('or_game_status'=>$_POST['status']));
		}else if((int)$_POST['status'] == 3){
			$result = M('Order')->where(array('or_id'=>$_POST['orderId']))->save(array('or_game_status'=>3,'or_status'=>2,'or_end_time'=>time(),'or_end_msg'=>'自助结束','or_password'=>'******'));
			if($order['or_device_id']!=null){
				M('Device')->where(array('dev_id'=>$order['or_device_id']))->save(array('dev_status'=>1));
			}
		}
		M('Device')->where(array('dev_id'=>$order['or_device_id']))->save(array('dev_tag'=>1));
		ApiResult(200);
	}

	/* 获取订单信息 */
	public function getOrderInfo(){
		$mustData = array(
			'or_id'=>$_POST['orderId'],
		);
		CheckMustData($mustData);
		$data = M('Order')->where(array('or_id'=>$_POST['orderId']))->find();
		$game_status = C('game_status');
		$data['or_game_status_name'] = $game_status[$data['or_game_status']];
        $data['or_create_time_diff'] = timediff($data['or_create_time'],time());
        $data['or_create_time'] = date("Y-m-d H:i:s",$data['or_create_time']);
		ApiResult(200,$data);
	}
	/* 获取订单进度 */
	public function getOrderSchedule(){
		$mustData = array(
			'or_id'=>$_POST['orderId'],
		);
		CheckMustData($mustData);
		$dataList = M('OrderSchedule')->where(array('os_order_id'=>$_POST['orderId']))->order('os_id desc')->limit(3)->select();
		foreach ($dataList as $key => $value) {
			$dataList[$key]['os_create_time'] = date("H:i:s",$value['os_create_time']);
		}
		$defualt = array(
			'os_msg'=>'',
			'os_create_time'=>''
		);
		$result = array(
			'msg_a'=>empty($dataList[0])?$defualt:$dataList[0],
			'msg_b'=>empty($dataList[1])?$defualt:$dataList[1],
			'msg_c'=>empty($dataList[2])?$defualt:$dataList[2],
		);
		ApiResult(200,$result);
	}
	
	/* 获取参数和值 */
	public function getParams(){
		$mustData = array(
			'or_id'=>$_POST['orderId'],
		);
		CheckMustData($mustData);
		$dataList = M('Order')->where(array('or_id'=>$_POST['orderId']))->find();
		if(empty($dataList)){
			ApiResult(300);
		}
		$selecdParams = $dataList['or_param'];
		$selecdParams = json_decode($selecdParams,true);
		$parameterList = M('Parameter')->select();
		foreach ($parameterList as $key => $value) {
			$parameValue = M("ParameterValue")->where(array('pav_pa_id'=>$value['pa_id']))->order('pav_value asc')->select();
			$parameterList[$key]['value'] = $parameValue;
			$parameterList[$key]['selected_id'] = $selecdParams[$value['pa_key']]['pav_id'];
			foreach ($parameValue as $k => $v) {
				if($v['pav_value']==$selecdParams[$value['pa_key']]){
					$parameterList[$key]['selected_name'] = $v['pav_name'];
					$parameterList[$key]['selected_value'] = $v['pav_value'];
				}
			}
		}
		ApiResult(200,array('dataList'=>$parameterList));
	}

	/* 获取订单设备列表 */
	public function getOrderList(){
		$mustData = array(
			'userId'=>$_POST['userId'],
		);
		CheckMustData($mustData);

		$limit = I("pageSize", 60, "intval");
        $page = I("pageCurrent", 1, "intval");
        $order_model = M("Order");
        $condition['or_user_id'] = $_POST['userId'];
        $order = "or_create_time desc";
        if($_POST['or_status']!=null&&$_POST['or_status']!=''){
        	$condition['or_status'] = array('eq',$_POST['or_status']);
        	if($_POST['or_status']==2){
        		$order = "or_end_time desc";
        	}
        }else{
        	$condition['or_status'] = array('neq',2);
        }
        if((int)$limit==0){
        	$limit=30;
        }
        if((int)$page==0){
        	$page=1;
        }
        $count = $order_model->where($condition)->count();
        $dataList = $order_model->field('or_serial_number,or_deduction_value,or_create_time,or_vip,or_game_status,or_end_time,or_end_msg,or_account,or_id')->where($condition)->limit($limit)->page($page)->order($order)->select();
        foreach ($dataList as $key => $value) {
        	$game_status = C('game_status');
        	$dataList[$key]['or_game_status_name'] = $game_status[$value['or_game_status']];
        	$dataList[$key]['or_create_time_diff'] = timediff($value['or_create_time'],time());
        	$dataList[$key]['or_create_time'] = date("Y-m-d H:i:s",$value['or_create_time']);
        	if($value['or_end_time']!=null&&$value['or_end_time']!=''){
        		$dataList[$key]['or_end_time'] = date("Y-m-d H:i:s",$value['or_end_time']);
        	}
        }
        $resultData = array(
        	'count'=>$count,
        	'dataList'=>$dataList
        );
        ApiResult(200,$resultData);
	}

	/* 库存检查 */
	public function checkStock(){
		$mustData = array(
			'versionId'=>$_POST['versionId'],
		);
		CheckMustData($mustData);

		$resultData = array(
			'ordinary'=>1,
			'vip'=>1
		);
		/* 检测设备库存 */
		$sysconfig = C('sysconfig');
		$stock_condition['sc_id'] = $sysconfig['stock'];
		$stock_data = M("SystemConfig")->where($stock_condition)->find();
		$deviceNum = M('Device')->where(array('dev_status'=>1,'dev_version_id'=>$mustData['versionId']))->count();/*获取空闲设备数*/
		$orderNum = M('Order')->where(array('or_status'=>0,'or_version_id'=>$mustData['versionId']))->count();

		/* 第二期更改 保留空闲取值更改为 取对应版本的保留空闲 */
		$versionInfo = M("Version")->where(array('ve_id'=>$mustData['versionId']))->find();
		if(empty($versionInfo)){
			ApiResult(310,$resultData);
		}
		$stock_data['sc_value_2'] = ($versionInfo['ve_retain_idle']!=null)?$versionInfo['ve_retain_idle']:0;
		if($orderNum<$deviceNum){
			if(($deviceNum-$orderNum)<=(int)$stock_data['sc_value_2']){
				$resultData['vip']=0;
			}
			$orderNum_def = M('Order')->where(array('or_status'=>array('neq',2),'or_vip'=>0))->count();
			/* 获取非完成的普通设备订单数 */
			if((int)$stock_data['sc_value']>$orderNum_def){
				if(($deviceNum-$orderNum)<=(int)$stock_data['sc_value_2']){
					$resultData['ordinary']=0;
				}
			}else{
				$resultData['ordinary']=0;
			}
		}else{
			$resultData = array(
				'ordinary'=>0,
				'vip'=>0
			);
		}
		ApiResult(200,$resultData);
	}
	/* 设置订单备注 */
	public function editOrderRemark(){
		$mustData = array(
			'userId'=>$_POST['userId'],
			'or_id'=>$_POST['or_id'],
			'or_remark'=>$_POST['or_remark'],
		);
		CheckMustData($mustData);
		$orderCondition = array(
			'or_id'=>$_POST['or_id'],
			'or_user_id'=>$_POST['userId'],
		);
		$order_info = M("Order")->where($orderCondition)->find();
		if(empty($order_info)){

		}
		M("Order")->where($orderCondition)->save(array('or_remark'=>htmlspecialchars($_POST['or_remark'])));
		ApiResult(200);
	}

 	/* 申请订单 */
	public function applyOrder(){
		$mustData = array(
			'userId'=>$_POST['userId'],
			'version'=>$_POST['version'],
			'account'=>$_POST['account'],
			'password'=>$_POST['password'],
			'isVip'=>$_POST['isVip'],
			'versionId'=>$_POST['versionId'],
		);
		CheckMustData($mustData);

		/* 检测设备库存 */
		$sysconfig = C('sysconfig');
		$stock_condition['sc_id'] = $sysconfig['stock'];
		$stock_data = M("SystemConfig")->where($stock_condition)->find();
		$deviceNum = M('Device')->where(array('dev_status'=>1,'dev_version_id'=>$mustData['versionId']))->count();/*获取空闲设备数*/
		$orderNum = M('Order')->where(array('or_status'=>0,'or_version_id'=>$mustData['versionId']))->count();

		$versionInfo = M("Version")->where(array('ve_id'=>$mustData['versionId']))->find();
		if(empty($versionInfo)){
			ApiResult(310,$resultData);
		}
		$stock_data['sc_value_2'] = ($versionInfo['ve_retain_idle']!=null)?$versionInfo['ve_retain_idle']:0;
		if($orderNum<$deviceNum){
			if($_POST['isVip']==1){/* VIP设备 */
				if(($deviceNum-$orderNum)<=(int)$stock_data['sc_value_2']){
					ApiResult(308);
				}
			}else{/* 普通设备 */
				$orderNum_def = M('Order')->where(array('or_status'=>array('neq',2),'or_vip'=>0))->count();
				/* 获取非完成的普通设备订单数 */
				if((int)$stock_data['sc_value']>$orderNum_def){
					if(($deviceNum-$orderNum)<=(int)$stock_data['sc_value_2']){
						ApiResult(308);
					}
				}else{
					ApiResult(308);
				}
			}
		}else{
			ApiResult(308);
		}
		/* 获取扣费信息 */
		$sysconfig = C('sysconfig');
		$deduction_condition['sc_id'] = $sysconfig['payment'];
		$deduction_data = M("SystemConfig")->where($deduction_condition)->find();
		$deduction_value = ((int)$_POST['isVip']==1)?(int)$deduction_data['sc_value_2']:(int)$deduction_data['sc_value'];

		/* 判断用户账户信息 */
		$userInfo = M('User')->where(array('us_id'=>$_POST['userId']))->find();
		if(empty($userInfo)){
			ApiResult(306);
		}
		if((int)$_POST['isVip']==1&&((int)$userInfo['us_cloud_money']<$deduction_value)){
			ApiResult(309);
		}else if((int)$_POST['isVip']==0&&((int)$userInfo['us_award_money']<$deduction_value)){
			ApiResult(309);
		}

		/* 拼装默认参数 */
		$parameterData = array();
		$parameterList = M('Parameter')->select();
		foreach ($parameterList as $key => $value) {
			$parameValue = M("ParameterValue")->where(array('pav_pa_id'=>$value['pa_id']))->order('pav_value asc')->find();
			$parameterData[$value['pa_key']] = $parameValue['pav_value'];
		}
		$model = M();
        $model->startTrans();
		/* 拼装订单数据 */
		$orderData = array(
			'or_serial_number'=>date('YmdHis').getRandChar(4,2),
			'or_user_id'=>$_POST['userId'],
			'or_account'=>$_POST['account'],
			'or_password'=>$_POST['password'],
			'or_create_time'=>time(),
			'or_vip'=>$_POST['isVip'],
			'or_deduction_nums'=>1,
			'or_deduction_value'=>$deduction_value,
			'or_param'=>json_encode($parameterData),
			'or_version'=>$_POST['version'],
			'or_version_id'=>$mustData['versionId'],
			'or_remark'=>$_POST['account'],
		);
		if((int)$_POST['isVip']==1){
			$user_result = $model->table(C('DB_PREFIX').'user')->where(array('us_id'=>$_POST['userId']))->save(array('us_cloud_money'=>(int)$userInfo['us_cloud_money']-$deduction_value));
		}else{
			$user_result = $model->table(C('DB_PREFIX').'user')->where(array('us_id'=>$_POST['userId']))->save(array('us_award_money'=>(int)$userInfo['us_award_money']-$deduction_value));
		}
		$order_result = $model->table(C('DB_PREFIX').'order')->add($orderData);
		$scheduleData = array(
			'os_msg'=>'订单已提交,等待设备连接中',
			'os_order_id'=>$order_result,
			'os_create_time'=>time(),
		);
		$model->table(C('DB_PREFIX').'order_schedule')->add($scheduleData);
		if($order_result&&$user_result){
			$model->commit();
			ApiResult(200,array('os_order_id'=>$order_result));
		}else{
			$model->rollback();
			ApiResult(300);
		}
	}
}
?>